package com.example.demo.controller;

import com.example.demo.pojo.ResponseMessage;
import com.example.demo.pojo.User;
import com.example.demo.pojo.dto.UserDto;
import com.example.demo.service.IUserService;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


@RestController     //接口方法返回对象, 转换成json
@RequestMapping("/user")        // localhost:8088/user
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    @Autowired
    UserService userService;
//    rest风格接口
//    add

    @PostMapping            // 可以指定 @PostMapping("/add"), 这里不需要,POST默认增加
    public ResponseMessage<User> add(@Validated @RequestBody UserDto user){         //Validated 校验必须加.
        logger.info("userController========================");
        logger.info("user:" + user);
        User userCreated = userService.add(user);
        return ResponseMessage.success(userCreated);        //success是静态方法直接访问,不需要实例化ResponseMessage()
    }
//    modify
    @PutMapping
    public ResponseMessage<User> edit(@Validated @RequestBody UserDto user){
        User userModified = userService.edit(user);
        return ResponseMessage.success(userModified);
    }

//    delete
    @DeleteMapping("/{userId}")
    public ResponseMessage delete(@PathVariable Integer userId){
        userService.delete(userId);
        return ResponseMessage.success();
    }

//    get
    @GetMapping("/{userId}")                //  localhost:8888/user/1
    public ResponseMessage<User> get(@PathVariable Integer userId){     // @PathVariable 表示从url中获取参数.
        User user = userService.getUser(userId);
        return ResponseMessage.success(user);
    }

}
